<template>
  <div>
    <div id="mapContainer"></div>
    <div id="mapPanel"></div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
// import "../assets/mapicon/iconfont";
export default {
  data() {
    return {
      //此处不声明 map 对象，可以直接使用 this.map赋值或者采用非响应式的普通对象来存储。
      //map:null,
    };
  },
  mounted() {
    this.getData();
  },

  methods: {
    // 获取数据
    getData() {
      var routeParmas = this.$route.params;
      let url = `map/infowindow/${routeParmas.id}`;
      this.axios.get(url).then(res => {
        //DOM初始化完成进行地图初始化
        this.initMap(res);
      });
    },
    // 初始化地图
    initMap(res) {
      // console.log(res);
      var infoWindowData = res.data.data[0];
      var longitude = +infoWindowData.longitude;
      var latitude = +infoWindowData.latitude;
      var mypop = this.$toast;
      window._AMapSecurityConfig = {
        securityJsCode: "bec06cd3cf1832aaae00d81dc97a6889",
      };
      AMapLoader.load({
        key: "775c192ff6dbce06db79fe1bd553f73e",
        version: "2.0",
        plugins: [
          "AMap.ToolBar",
          "AMap.Scale",
          "AMap.ControlBar",
          "AMap.HawkEye",
        ], // 需要使用的的插件列表
      })
        .then(AMap => {
          // 设置经纬度坐标
          var lnglat = new AMap.LngLat(longitude, latitude);
          let map = new AMap.Map("mapContainer", {
            resizeEnable: true,
            zoom: 14, //地图初始的缩放倍数
            center: lnglat, //初始化后地图展示的中心位置
          });

          // 添加插件
          var scale = new AMap.Scale();
          var toolBar = new AMap.ToolBar({
            position: {
              top: "110px",
              right: "50px",
            },
          });
          var controlBar = new AMap.ControlBar({
            visible: true,
            position: {
              top: "10px",
              right: "20px",
            },
          });
          var overView = new AMap.HawkEye({
            visible: true,
            position: {
              bottom: "20px",
              right: "20px",
            },
          });
          map.addControl(scale);
          map.addControl(toolBar);
          map.addControl(controlBar);
          map.addControl(overView);

          // 创建一个 marker Icon
          var markerIcon = new AMap.Icon({
            // 图标尺寸
            size: new AMap.Size(32, 32),
            // 图标的取图地址
            image: "/img/hospital.png",
            // 图标所用图片大小
            imageSize: new AMap.Size(32, 32),
            // 图标取图偏移量
            // imageOffset: new AMap.Pixel(-9, -3),
          });
          // 创建一个 Marker 实例：
          // 将 icon 传入 marker
          var marker = new AMap.Marker({
            position: lnglat, // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
            title: `${res.name}`,
            icon: markerIcon,
            offset: new AMap.Pixel(-13, -30),
          });
          // 将创建的点标记添加到已有的地图实例：
          map.add(marker);

          // 信息窗体的内容
          // 创建 infoWindow 实例
          // 获取用户当前位置
          var title = `${infoWindowData.name}`,
            content = [];
          content.push(
            `<div><img src='http://tpc.googlesyndication.com/simgad/5843493769827749134'></div><div><span>地址：${infoWindowData.addr}</span>`
          );
          content.push(`<span>门诊时间：${infoWindowData.office_hours}</span>`);
          content.push(`<span>电话：${infoWindowData.tel}</span></div>`);
          content.push(
            `<div><div id="getLngLat"><img src='/img/dirnew_white.png' /><span>去这里</span></div></div>`
          );
          var infoWindow = new AMap.InfoWindow({
            //创建信息窗体
            isCustom: true, //使用自定义窗体
            content: this.createInfoWindow(map, title, content.join(" ")), //信息窗体的内容可以是任意html片段
            offset: new AMap.Pixel(16, -45),
          });
          // 默认打开信息窗体
          infoWindow.open(map, marker.getPosition());
          var onMarkerClick = function (e) {
            if (infoWindow.getIsOpen()) {
              infoWindow.close();
            } else {
              // 打开信息窗体
              infoWindow.open(map, marker.getPosition()); //打开信息窗体
              //e.target就是被点击的Marker
            }
          };
          marker.on("click", onMarkerClick); //绑定click事件

          //  点击去这里 跳转路线
          var goMapPath = function () {
            mypop({
              message: "加载中...",
              forbidClick: true,
              loadingType: "spinner",
            });
            let name = infoWindowData.name;
            // longitude latitude;
            // 获取用户当前位置
            let geoloc = window.navigator.geolocation;
            geoloc.getCurrentPosition(
              success => {
                let fromLongitude = success.coords.longitude
                let fromLatitude = success.coords.fromLatitude
                // 成功后执行
                window.location = `https://uri.amap.com/navigation/navigation?from=${fromLongitude},${fromLatitude},我的位置&to=${longitude},${latitude},${name}&mode=car&policy=1&src=mypage&coordinate=gaode&callnative=1`;
              },
              err => {
                window.location = `https://uri.amap.com/navigation/navigation?to=${longitude},${latitude},${name}&mode=car&policy=1&src=mypage&coordinate=gaode&callnative=1`;
              },
              { timeout: 5000 }
            );
          };
          document
            .querySelector("#getLngLat")
            .addEventListener("click", goMapPath);
        })
        .catch(e => {
          console.log(e);
        });
    },
    //构建自定义信息窗体
    createInfoWindow(map, title, content) {
      var info = document.createElement("div");
      info.className = "custom-info input-card content-window-card";
      //可以通过下面的方式修改自定义窗体的宽高
      info.style.width = "320px";
      // 定义顶部标题
      var top = document.createElement("div");
      var titleD = document.createElement("div");
      var closeX = document.createElement("img");
      top.className = "info-top";
      titleD.innerHTML = title;
      closeX.src = "https://webapi.amap.com/images/close2.gif";
      closeX.onclick = () => map.clearInfoWindow();

      top.appendChild(titleD);
      top.appendChild(closeX);
      info.appendChild(top);
      // 定义中部内容
      var middle = document.createElement("div");
      middle.className = "info-middle";
      middle.style.backgroundColor = "white";
      middle.innerHTML = content;
      info.appendChild(middle);
      // 定义底部内容
      var bottom = document.createElement("div");
      bottom.className = "info-bottom";
      bottom.style.position = "relative";
      bottom.style.top = "0px";
      bottom.style.margin = "0 auto";
      var sharp = document.createElement("img");
      sharp.src = "https://webapi.amap.com/images/sharp.png";
      bottom.appendChild(sharp);
      info.appendChild(bottom);
      return info;
    },
  },
};
</script>

<style lang="scss">
body {
  margin: 0;
  padding: 0;
}
a {
  text-decoration: none;
}
#mapContainer {
  margin: 0;
  padding: 0;
  width: 100vw;
  height: 100vh;
}
#mapPanel {
  position: absolute;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 10px;
  right: 10px;
  width: 280px;
}

// 信息框样式
.content-window-card {
  position: relative;
  box-shadow: none;
  bottom: 0;
  left: 0;
  width: auto;
  padding: 0;
  .custom-info {
    border: solid 1px silver;
  }
  div.info-top {
    position: relative;
    background: none repeat scroll 0 0 #f9f9f9;
    border-bottom: 1px solid #ccc;
    border-radius: 5px 5px 0 0;
  }

  div.info-top div {
    display: inline-block;
    color: #333333;
    font-size: 14px;
    font-weight: bold;
    line-height: 31px;
    padding: 0 10px;
  }

  div.info-top img {
    position: absolute;
    top: 10px;
    right: 10px;
    transition-duration: 0.25s;
  }

  div.info-top img:hover {
    box-shadow: 0px 0px 5px #000;
  }

  div.info-middle {
    font-size: 12px;
    padding: 10px 8px;
    line-height: 20px;
    display: flex;
    justify-content: space-between;
    > div:nth-child(1) {
      overflow: hidden;
      min-width: 80px;
      img {
        height: 100%;
      }
    }
    > div:nth-child(2) {
      margin: 0 4px;
      span {
        display: block;
      }
    }
    > div:nth-child(3) {
      > div {
        width: 52px;
        height: 52px;
        background-color: #36c14c;
        border-radius: 50%;
        margin-top: 9px;
        img {
          margin: 0 auto;
          display: block;
          width: 20px;
          padding-top: 4px;
        }
        span {
          display: block;
          text-align: center;
          color: #fff;
          margin-left: 0px;
        }
      }
    }
  }

  div.info-bottom {
    height: 0px;
    width: 100%;
    clear: both;
    text-align: center;
  }

  div.info-bottom img {
    position: relative;
    z-index: 104;
  }
}
</style>
